package cz.byteworks.sandbox.html5.newsbox.app;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import cz.byteworks.sandbox.html5.newsbox.jms.JmsMessageReceiver;
import cz.byteworks.sandbox.html5.newsbox.model.NewsMessage;

@Configuration
@ComponentScan({"cz.byteworks.sandbox.html5.newsbox.dao", "cz.byteworks.sandbox.html5.newsbox.service", "cz.byteworks.sandbox.html5.newsbox.servlet", "cz.byteworks.sandbox.html5.newsbox.jms"})
public class SpringConfigBean {
    
    private static final String QUEUE = "Q_NEWS";
    private static final int WEB_CONTAINER_MESSAGE_QUEUE_SIZE = 10;
    private static final String BROKER_URL = "tcp://localhost:61616";
    
    @Bean
    public ActiveMQConnectionFactory amqConnectionFactory() {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
        return factory;
    }
    
    @Bean
    public CachingConnectionFactory connectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory(amqConnectionFactory());
        factory.setReconnectOnException(true);
        return factory;
    }
    
    @Bean
    public ActiveMQQueue defaultDestination() {
        return new ActiveMQQueue(QUEUE);
    }
    
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate template = new JmsTemplate(connectionFactory());
        template.setDefaultDestination(defaultDestination());
        return template;
    }
    
    @Bean
    public JmsMessageReceiver messageReceiver() {
        return new JmsMessageReceiver();
    }
    
    @Bean
    public DefaultMessageListenerContainer messageListenerContainer() {
        JmsMessageReceiver receiver = messageReceiver();
        DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory());
        listenerContainer.setDestinationName(QUEUE);
        listenerContainer.setMessageListener(receiver);
 //       listenerContainer.setExceptionListener(receiver);
        return listenerContainer;
    }
    
    @Bean
    public FixedSizeQueue<NewsMessage> webContainerMessageQueue() {
        return new FixedSizeQueue<NewsMessage>(WEB_CONTAINER_MESSAGE_QUEUE_SIZE);
    }

}
